<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="index.css">
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>

<body>
  <div id="app"></div>
  <script type="text/babel">

    // 定义函数式组件
    const TodoList = () => {

      const [inputText, setInputText] = React.useState('')
      //文本框变化
      const handleInputChange = (e) => {
        setInputText(e.target.value);
      };


      const [todoList, setTodoList] = React.useState([])

      //添加todo
      const addTodo = () => {
        todoList.unshift({ key: new Date().getTime(), content: inputText })
        setInputText('')
        setTodoList([...todoList]) 
      }

      //删除todo
      const deleteTodo = (key) => {
        const newTodos=todoList.filter(item=>item.key!==key)
        setTodoList(newTodos)
      }


      return (
        <div className='todo-list'>
          <h1>Todo List</h1>
          <div className='content'>
            <input type="text" value={inputText} onChange={handleInputChange}></input>
            <button onClick={addTodo}>Add</button>
          </div>
          <ul>
            {todoList.map((item)=>(
              <li key={item.key}>{item.content}<button onClick={()=>deleteTodo(item.key)}>Delete</button></li>
            ))}
          </ul>
        </div>
      );
    };

    // 将组件渲染到指定的DOM元素（id为app的元素）上
    ReactDOM.render(<TodoList />, document.getElementById('app'));
  </script>
</body>

</html>